package com.tax.infrastructure.util;

import com.tax.config.exception.BusinessException;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * duandehui
 */
@Slf4j
public class CompletableFutureUtil {

    /**
     *
     * @param futures
     * @param logMessage
     */
    public static void blockWaitingUntilFinished(List<CompletableFuture<Void>> futures,String logMessage){
        try{
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        }catch (BusinessException e){
            repackageMessage(e,logMessage);
        }catch (Exception e){
            otherExceptionHandler(e,logMessage);
        }
    }

    /**
     *
     * @param future
     * @param logMessage
     */
    public static void blockWaitingUntilFinished(CompletableFuture<Void> future,String logMessage){
        try{
            future.join();
        }catch (BusinessException e){
            repackageMessage(e,logMessage);
        }catch (Exception e){
            otherExceptionHandler(e,logMessage);
        }
    }

    private static void otherExceptionHandler(Exception e, String logMessage) {
        Throwable throwable=e.getCause();
        log.error("并发处理堆栈异常信息,Exception={},logMessage={}", ThrowableUtil.stackTraceToString(e),logMessage);
        if (throwable instanceof BusinessException){
            repackageMessage((BusinessException) throwable,logMessage);
        }
        throw new BusinessException(500);
    }

    private static void repackageMessage(BusinessException e, String logMessage) {
        log.warn("repackageMessage,Exception={},logMessage={}", ThrowableUtil.stackTraceToString(e),logMessage);
        throw new BusinessException(e.getErrorCode(),e.getMessage());
    }
}
